<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="采购单号" prop="caigouDanhao">
        <el-input
          v-model="queryParams.caigouDanhao"
          placeholder="请输入采购单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请人" prop="shenqingName">
        <el-input
          v-model="queryParams.shenqingName"
          placeholder="请输入申请人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请日期" prop="shenqingDate">
        <el-date-picker clearable
          v-model="queryParams.shenqingDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择申请日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="采购人" prop="caigouName">
        <el-input
          v-model="queryParams.caigouName"
          placeholder="请输入采购人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采购日期" prop="caigouDate">
        <el-date-picker clearable
          v-model="queryParams.caigouDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择采购日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="审核状态" prop="shenheState">
        <el-select v-model="queryParams.shenheState" placeholder="请选择审核状态" clearable>
          <el-option
            v-for="dict in dict.type.shenhe_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    <!--  <el-form-item label="总价格" prop="totalPrice">
        <el-input
          v-model="queryParams.totalPrice"
          placeholder="请输入总价格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="总数量" prop="totalNum">
        <el-input
          v-model="queryParams.totalNum"
          placeholder="请输入总数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:caigouMain:add']"
        >采购单申请</el-button>
      </el-col>
 <!--     <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:caigouMain:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:caigouMain:remove']"
        >撤销</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:caigouMain:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="caigouMainList" @selection-change="handleSelectionChange">
<!--
      <el-table-column type="selection" width="55" align="center" />
-->
      <el-table-column label="采购单号" width="150" align="center" prop="caigouDanhao">
        <template scope="scope">
          <div style="cursor:pointer;text-decoration:underline;color: blue" class="caigouDanhao" @click="rowClickInfo(scope.row)">{{ scope.row.caigouDanhao }}</div>
        </template>
      </el-table-column>
      <el-table-column label="申请事由" show-overflow-tooltip width="150" align="center" prop="shenqingShiyou" />
      <el-table-column label="审核状态" align="center" prop="shenheState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.shenhe_state" :value="scope.row.shenheState"/>
        </template>
      </el-table-column>
<!--
      <el-table-column label="总价格" align="center" prop="totalPrice" />
-->
      <el-table-column label="总数量" align="center" prop="totalNum" />
      <el-table-column label="申请人" align="center" prop="shenqingName" />
      <el-table-column width="120" label="申请人电话" align="center" prop="shenqingTel" />
      <el-table-column label="申请日期" align="center" prop="shenqingDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.shenqingDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采购人" align="center" prop="caigouName" />
      <el-table-column width="120" label="采购人电话" align="center" prop="caigouTel" />
      <el-table-column label="采购日期" align="center" prop="caigouDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.caigouDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采购状态" align="center" prop="caigouState">
        <template scope="scope">
          <dict-tag :options="dict.type.caigou_state" :value="scope.row.caigouState"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" show-overflow-tooltip align="center" prop="remark" />
      <el-table-column label="操作"  width="100" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.shenheState == 0"
            v-hasPermi="['business:caigouMain:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="scope.row.shenheState == 0"
            v-hasPermi="['business:caigouMain:remove']"
          >撤销</el-button>
        </template>
      </el-table-column>

    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" style="margin-top: -20px" label-width="80px">
        <el-row>
          <el-col :span="12">
          <el-form-item label="申请事由" prop="shenqingShiyou">
            <el-input   v-model="form.shenqingShiyou" placeholder="请输入申请事由" />
          </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购人"  prop="caigouName">
              <el-input readonly   v-model="form.caigouName" style="width: 70%" placeholder="请输入采购人" />
              <el-button
                type="primary"
                plain
                icon="el-icon-zoom-in"
                size="mini"
                @click="changeSelect"
              >选择用户</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="caigouTel">
              <el-input readonly   v-model="form.caigouTel" placeholder="请输入采购人联系方式" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购日期" prop="caigouDate">
              <el-date-picker
                v-model="form.caigouDate"
                type="date"
                placeholder="请输入采购日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
          <el-row>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input style="width: 500px"  type="textarea" v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <CaigouDetail ref="caigouDetail"></CaigouDetail>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
<!--    采购单详情-->
      <el-dialog :close-on-click-modal="false" :title="caigouTitle" :visible.sync="caigouOpen"  width="800px" append-to-body>
        <button v-print="printObj">打印</button>
        <div id="main2" style="width: 100%">
          <div style="width: 100%;text-align: center;font-size: 24px;margin-bottom:5px;">泰康锻造股份有限公司</div>
          <div style="width: 100%;text-align: center;font-size: 20px;margin-bottom:10px;">采购申请单</div>
          <el-table v-loading="caiLoading" :data="caigouList">
            <el-table-column label="采购单号" width="100" align="center" prop="caigouDanhao"  />
            <el-table-column label="采购日期" width="100" align="center" prop="caigouDate"  />
            <el-table-column label="物料名称" width="100" align="center" prop="itemName"  />
            <el-table-column label="物料编号" width="100" align="center" prop="itemCode"  />
            <el-table-column label="物料分类" width="100" align="center" prop="className"  />
            <el-table-column label="规格" width="100" align="center" prop="spec"  />
            <el-table-column label="单位" width="50" align="center" prop="unit"  />
            <el-table-column label="采购数量" width="80" align="center" prop="caigouNum"  />
          <!--  <el-table-column label="单价（元）" width="80" align="center" prop="unitPrice"  />
            <el-table-column label="总价（元）" width="80" align="center" prop="totalPrice"  />-->
<!--            <el-table-column label="经办人" width="80" align="center" prop="createBy"  />-->
          </el-table>
          <div style="text-align: right"><span style="font-size: 18px;font-weight: 800">总数量：</span><span style="margin-right:40px">{{zsl}}</span></div>
        </div>
      </el-dialog>
    <!--选择用户-->
    <el-dialog :close-on-click-modal="false" :title="user.title" :visible.sync="user.open" width="1000px" append-to-body>
      <SelectUser ref="selectUser"></SelectUser>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUser">选 择</el-button>
        <el-button @click="user.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCaigouMain, getCaigouMain, delCaigouMain, addCaigouMain, updateCaigouMain } from "@/api/business/caigouMain";
import CaigouDetail from './caigouDetail';
import SelectUser from '@/views/system/user/selectUser';
import {caigouInfo} from "@/api/base/danInfo";
export default {
  components: {
    CaigouDetail,
    SelectUser
  },
  name: "CaigouMain",
  dicts: ['shenhe_state','caigou_state'],
  data() {
    return {
      printObj: {
        id: "main2",    // 这里是要打印元素的ID
        popTitle: '',  // 打印的标题
        extraCss: '',  // 打印可引入外部的一个 css 文件
        extraHead: ''  // 打印头部文字
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      caigouDanhaos: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      zsl:0,
      // 采购表格数据
      caigouMainList: [],
      // 弹出层标题
      title: "",
      user:{
        title: "",
        open: false,
      },
      caigouTitle:'',
      caigouOpen:false,
      caigouList:[],
      caiLoading:true,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        caigouDanhao: null,
        shenqingName: null,
        shenqingDate: null,
        caigouName: null,
        caigouDate: null,
        shenheState: null,
        totalPrice: null,
        totalNum: null,
      },
      // 表单参数
      form: {
        infoList:[]
      },

      // 表单校验
      rules: {
        shenqingShiyou: [
          { required: true, message: "申请事由不能为空", trigger: "blur" }
        ],
       /* caigouName: [
          { required: true, message: "采购人不能为空", trigger: "blur" }
        ],
        caigouDate: [
          { required: true, message: "采购日期不能为空", trigger: "blur" }
        ],*/
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询采购列表 */
    getList() {
      this.loading = true;
      listCaigouMain(this.queryParams).then(response => {
        this.caigouMainList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        caigouDanhao: null,
        shenqingShiyou: null,
        shenqingName: null,
        shenqingTel: null,
        shenqingDate: null,
        caigouName: null,
        caigouTel: null,
        caigouDate: null,
        shenheState: null,
        totalPrice: null,
        totalNum: null,
        fapiaoImg: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        remark: null,
        deptId: null
      };
      this.resetForm("form");
    },
    // 点击订单号展示详情
    rowClickInfo(row){
      // this.caiLoading = true
      caigouInfo(row.caigouDanhao).then(res=>{
        // console.log(res)
        this.caigouList = res.data.caigouDetail
        this.zsl = 0
        for(let i=0;i<this.caigouList.length;i++){
          this.zsl += this.caigouList[i].caigouNum
        }
        console.log(this.zsl)
      })
      this.caigouTitle = ''
      this.caigouOpen = true
      this.caiLoading = false
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.caigouDanhaos = selection.map(item => item.caigouDanhao)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "采购申请单";
      setTimeout(() => {
        this.$refs.caigouDetail.listReset();
      }, 10);
    },
    changeSelect(){
      this.user.open = true;
      this.user.title = "选择用户";
    },
    submitUser(){
      this.form.caigouName=this.$refs.selectUser.nickNames.toString();
      this.form.caigouTel=this.$refs.selectUser.phonenumbers.toString();
      this.user.open = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      const caigouDanhao = row.caigouDanhao || this.caigouDanhaos
      getCaigouMain(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改采购申请单";
        setTimeout(() => {
          this.$refs.caigouDetail.getCgInfoList(caigouDanhao.toString());
        }, 5);
      });
    },
    /** 提交按钮 */
    submitForm() {
      let caigouDetailList= this.$refs.caigouDetail.caigouDetailList;
      this.form.infoList=caigouDetailList;
      if(caigouDetailList.length==0){
        this.$modal.alertWarning('请选择物料')
        return;
      }
      for(var i=0;i<caigouDetailList.length;i++){
        if(caigouDetailList[i].caigouNum==''||caigouDetailList[i].caigouNum==null||caigouDetailList[i].caigouNum==undefined){
          this.$modal.alertWarning('请输入采购数量')
          return;
        }
     /*   if(caigouDetailList[i].unitPrice==''||caigouDetailList[i].unitPrice==null||caigouDetailList[i].unitPrice==undefined){
          this.$modal.alertWarning('请输入采购单价')
          return;
        }*/
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCaigouMain(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCaigouMain(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 撤销按钮操作 */
    handleDelete(row) {
      const danhao = row.caigouDanhao
      this.$modal.confirm('是否确认撤销采购编号为"' + danhao + '"吗？').then(function() {
        return delCaigouMain(danhao);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("撤销成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/caigouMain/export', {
        ...this.queryParams
      }, `caigouMain_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style media="print">
  @page {
    size: landscape;
    margin: 3mm;
  }
  @media print {
    html {
      background-color: #ffffff;
      height: auto;
      margin: 0px;
    }
    body {
      border: solid 1px #ffffff;
      /* margin: 10mm 15mm 10mm 15mm; */
    }
    #main table {
      table-layout: auto !important;
    }
    #main .el-table__header-wrapper .el-table__header {
      width: 100% !important;
      border: solid 1px #f2f2f2;
    }
    #main .el-table__body-wrapper .el-table__body {
      width: 100% !important;
    }
    #main #pagetable table {
      table-layout: fixed !important;
    }
  }
</style>
